import requests
import pandas as pd
import json
import re
from datetime import datetime


def get_index_data_eastmoney(index_code="931079"):
    """
    使用东方财富网API获取指数数据
    """
    try:
        # 东方财富指数API
        url = f"http://push2.eastmoney.com/api/qt/stock/get"
        params = {
            'secid': f'{index_code}',  # 0表示深交所
            'ut': 'fa5fd1943c7b386f172d6893dbfba10b',
            'invt': 2,
            'fields': 'f43,f44,f45,f46,f60,f84,f85,f86,f169,f170'
        }
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'http://quote.eastmoney.com/'
        }
        response = requests.get(url, params=params, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        print(response)
        if response.status_code == 200:
            data = response.json()
            if data['data']:
                stock_data = data['data']
                return {
                    '指数代码': index_code,
                    '指数名称': stock_data.get('f84', 'N/A'),
                    '当前价格': stock_data.get('f43', 'N/A'),
                    '涨跌幅': stock_data.get('f170', 'N/A'),
                    '更新时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
        return None

    except Exception as e:
        print(f"东方财富接口获取失败: {e}")
        return None


# 测试
result = get_index_data_eastmoney("931079")
if result:
    print("东方财富数据获取成功:")
    for key, value in result.items():
        print(f"{key}: {value}")
else:
    print("东方财富接口获取失败")